package com.robot.merchant.controller;

import com.alibaba.fastjson.JSON;
import com.robot.merchant.client.GoodsClient;
import com.robot.merchant.pojo.Store;
import com.robot.merchant.pojo.client.Goods;
import com.robot.merchant.pojo.client.GoodsCategory;
import com.robot.merchant.service.StoreService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * goods控制器层
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private StoreService storeService;
    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * store表status 0-禁用 1-启用
     */
    private final String storeStatusEnable = "1";

    /**
     * goods表的on_sale 上下架状态 0-下架 1-上架
     */
    private final String goodsOnSaleFailed = "0";
    private final String goodsOnSaleSuccess = "1";
    /**
     * goods表的is_coupon 是否卡券 0-否,1-是
     */
    private final String goodsIsNotCoupon = "0";
    private final String goodsIsCoupon = "1";


    /**
     * 商品分类列表并分页
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "goodsCategory/{page}/{size}", method = RequestMethod.GET)
    public Result findGoodsCategories(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(goodsClient.thirdFindGoodsCategoryBySearch(new HashMap(1), page, size)));
    }

    /**
     * 商品分类列表
     *
     * @return
     */
    @RequestMapping(value = "goodsCategory", method = RequestMethod.GET)
    public Result findGoodsCategories() {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parse(goodsClient.thirdFindGoodsCategory()));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findGoodsBySearch/{page}/{size}", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result findGoodsBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        searchMap.put("storeId", claims.getId());
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(goodsClient.thirdFindGoodsBySearch(searchMap, page, size)));
    }

    /**
     * 通过categoryId查询goods列表并分页
     *
     * @param categoryId
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findGoodsByCategoryId/{categoryId}/{page}/{size}", method = RequestMethod.GET)
    public Result findGoodsByCategoryId(@PathVariable String categoryId, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(goodsClient.thirdFindGoodsByCategoryIdAndStoreId(categoryId, claims.getId(), page, size)));
    }

    /**
     * 通过storeId查询goods列表并分页
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findGoodsByStoreId/{page}/{size}", method = RequestMethod.GET)
    public Result findGoodsByStoreId(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(goodsClient.thirdFindGoodsByStoreId(claims.getId(), page, size)));
    }

    /**
     * 通过ID查询商品详情
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "findGoodsById/{id}", method = RequestMethod.GET)
    public Result findGoodsById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsByIdAndStoreId(id, claims.getId()), Goods.class);
        if (goodsInDb == null) {
            return new Result(StatusCode.ERROR_GOODS_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, goodsInDb);
    }

    /**
     * 增加商品
     *
     * @param goods
     */
    @RequestMapping(value = "addGoods", method = RequestMethod.POST)
    public Result addGoods(@RequestBody Goods goods) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        //添加时检查实体类各项属性
        Result result = checkPojoFieldsWhenAdd(goods);
        if (result != null) {
            return result;
        }

        //检查商品图
        Map<String, Object> map = checkUtil.checkImages(goods.getImages());
        Boolean flag = (Boolean) map.get("flag");
        if (!flag) {
            return new Result(StatusCode.ERROR_FILE_FORMAT, (String) map.get("message"));
        } else {
            goods.setImages((String) map.get("message"));
        }


        if (goods.getIsCoupon() == null || "".equals(goods.getIsCoupon())) {
            goods.setIsCoupon(goodsIsNotCoupon);
        }


        goods.setStoreId(claims.getId());
        goods.setStatus("0");
        goodsClient.thirdAddGoodsByGoods(JSON.toJSONString(goods));
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 编辑商品
     *
     * @param goods
     */
    @RequestMapping(value = "updateGoods/{id}", method = RequestMethod.PUT)
    public Result updateGoods(@RequestBody Goods goods, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断


        //修改时检查实体类各项属性
        Result result = checkPojoFieldsWhenUpdate(goods);
        if (result != null) {
            return result;
        }

        //检查商品图
        if (goods.getImages() != null && !"".equals(goods.getImages())) {
            Map<String, Object> map = checkUtil.checkImages(goods.getImages());
            Boolean flag = (Boolean) map.get("flag");
            if (!flag) {
                return new Result(StatusCode.ERROR_FILE_FORMAT, (String) map.get("message"));
            } else {
                goods.setImages((String) map.get("message"));
            }
        }

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsByIdAndStoreId(id, claims.getId()), Goods.class);
        logger.info("goodsInDb=" + goodsInDb);
        if (goodsInDb == null || goodsInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_GOODS_DOES_NOTE_EXIST);
        }

        goods.setCreatedAt(goodsInDb.getCreatedAt());
        UpdateUtil.copyNonNullProperties(goods, goodsInDb);
        goodsInDb.setId(id);
        goodsInDb.setStoreId(claims.getId());
        goodsInDb.setStatus("0");
        goodsInDb.setUpdatedAt(LocalDateTime.now());
        goodsClient.thirdUpdateGoodsByGoods(JSON.toJSONString(goodsInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 上下架商品
     *
     * @param id
     * @param onSale
     * @return
     */
    @RequestMapping(value = "onSaleGoods/{id}/{onSale}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result onSaleGoods(@PathVariable String id, @PathVariable String onSale) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsByIdAndStoreId(id, claims.getId()), Goods.class);
        if (goodsInDb == null || goodsInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_GOODS_DOES_NOTE_EXIST);
        }
        logger.info("onSale=" + onSale + ",and goodsInDb onSale=" + goodsInDb.getOnSale());
        if (goodsOnSaleFailed.equals(onSale) || goodsOnSaleSuccess.equals(onSale)) {
            if (goodsOnSaleSuccess.equals(onSale) && goodsOnSaleSuccess.equals(goodsInDb.getOnSale())) {
                return new Result(StatusCode.ERROR, "商品已经是上架状态了!");
            }
            if (goodsOnSaleFailed.equals(onSale) && goodsOnSaleFailed.equals(goodsInDb.getOnSale())) {
                return new Result(StatusCode.ERROR, "商品已经是下架状态了!");
            }
            if (goodsOnSaleSuccess.equals(onSale)) {
                goodsInDb.setStatus("0");
            }
            goodsInDb.setOnSale(onSale);
        } else {
            return new Result(StatusCode.ERROR_GOODS_ON_SALE_INVALID);
        }
        goodsClient.thirdUpdateGoodsByGoods(JSON.toJSONString(goodsInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);

    }

    /**
     * 软删除商品
     *
     * @param id
     */
    @RequestMapping(value = "deleteGoods/{id}", method = RequestMethod.PUT)
    public Result deleteGoods(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Goods goodsInDb = JSON.parseObject(goodsClient.thirdFindGoodsByIdAndStoreId(id, claims.getId()), Goods.class);
        if (goodsInDb == null || goodsInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_GOODS_DOES_NOTE_EXIST);
        }
        goodsInDb.setDeletedAt(LocalDateTime.now());
        goodsClient.thirdUpdateGoodsByGoods(JSON.toJSONString(goodsInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 添加时检查实体类各项属性
     *
     * @param goods
     * @return
     */
    public Result checkPojoFieldsWhenAdd(Goods goods) {
        if (goods.getCategoryId() == null || "".equals(goods.getCategoryId())) {
            return new Result(StatusCode.ERROR_GOODS_CATEGORY_NAME_REQUIRED);
        }
        if (JSON.parseObject(goodsClient.thirdFindGoodsCategoryById(goods.getCategoryId()), GoodsCategory.class) == null) {
            return new Result(StatusCode.ERROR_GOODS_CATEGORY_DOES_NOTE_EXIST);
        }
        if (goods.getName() == null || "".equals(goods.getName())) {
            return new Result(StatusCode.ERROR_GOODS_NAME_REQUIRED);
        }
        if (goods.getPrice() == null || "".equals(goods.getPrice())) {
            return new Result(StatusCode.ERROR_GOODS_PRICE_REQUIRED);
        }
        if (goods.getPrice().compareTo(BigDecimal.ZERO) == -1) {
            return new Result(StatusCode.ERROR_GOODS_PRICE_INVALID);
        }

        if (goods.getStock() == null || "".equals(goods.getStock())) {
            return new Result(StatusCode.ERROR_GOODS_STOCK_REQUIRED);
        }
        if (goods.getStock() < 0) {
            return new Result(StatusCode.ERROR_GOODS_STOCK_INVALID);
        }

        if (goods.getImages() == null || "".equals(goods.getImages())) {
            return new Result(StatusCode.ERROR_GOODS_IMAGES_REQUIRED);
        }

        if (!goodsIsCoupon.equals(goods.getIsCoupon()) && !goodsIsNotCoupon.equals(goods.getIsCoupon())) {
            return new Result(StatusCode.ERROR_GOODS_IS_COUPON_INVALID);
        }
        logger.info("addGoods's onSale=" + goods.getOnSale());
        if (goods.getOnSale() == null || "".equals(goods.getOnSale())) {
            return new Result(StatusCode.ERROR_GOODS_ON_SALE_REQUIRED);
        }
        if (!goodsOnSaleFailed.equals(goods.getOnSale()) && !goodsOnSaleSuccess.equals(goods.getOnSale())) {
            return new Result(StatusCode.ERROR_GOODS_ON_SALE_INVALID);
        }
        if (goods.getIntroduction() == null || "".equals(goods.getIntroduction())) {
            return new Result(StatusCode.ERROR_GOODS_INTRODUCTION_REQUIRED);
        }
        return null;
    }

    /**
     * 修改时检查实体类各项属性
     *
     * @param goods
     * @return
     */
    public Result checkPojoFieldsWhenUpdate(Goods goods) {
        if (goods.getCategoryId() != null && !"".equals(goods.getCategoryId()) && JSON.parseObject(goodsClient.thirdFindGoodsCategoryById(goods.getCategoryId()), GoodsCategory.class) == null) {
            return new Result(StatusCode.ERROR_GOODS_CATEGORY_DOES_NOTE_EXIST);
        }
        if (goods.getPrice() != null && !"".equals(goods.getPrice()) && goods.getPrice().compareTo(BigDecimal.ZERO) == -1) {
            return new Result(StatusCode.ERROR_GOODS_PRICE_INVALID);
        }
        if (goods.getStock() != null && !"".equals(goods.getStock()) && goods.getStock() < 0) {
            return new Result(StatusCode.ERROR_GOODS_STOCK_INVALID);
        }
        if (goods.getOnSale() == null || "".equals(goods.getOnSale())) {
            return new Result(StatusCode.ERROR_GOODS_ON_SALE_REQUIRED);
        }
        if (!goodsOnSaleFailed.equals(goods.getOnSale()) && !goodsOnSaleSuccess.equals(goods.getOnSale())) {
            return new Result(StatusCode.ERROR_GOODS_ON_SALE_INVALID);
        }
        return null;
    }

}
